import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;


import com.sun.lwuit.Command;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.DataChangedListener;
import com.sun.lwuit.events.SelectionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.ListModel;


public class ChatForm extends Form implements ActionListener{
	Vector Messages;
	List list;
	httprequest display;
	TextField chatspace;
	Command back;
	Command send;
	public ChatForm(String title, MIDlet parent)
	{
		super(title);
		display=(httprequest)parent;
		
		Messages=new Vector();
		
		this.setLayout(new BorderLayout());
		list = new List(new ListModel() {
			private int selection;
			public void setSelectedIndex(int arg0) {
				// TODO Auto-generated method stub
				selection = arg0;
			}
			
			public void removeSelectionListener(SelectionListener arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void removeItem(int arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void removeDataChangedListener(DataChangedListener arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public int getSize() {
				// TODO Auto-generated method stub
				return Messages.size();
			}
			
			public int getSelectedIndex() {
				// TODO Auto-generated method stub
				return selection;
			}
			
			public Object getItemAt(int arg0) {
				// TODO Auto-generated method stub
				if(arg0>Messages.size())
					return null;
				return Messages.elementAt(arg0);
			}
			
			public void addSelectionListener(SelectionListener arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void addItem(Object arg0) {
				// TODO Auto-generated method stub	
				TheMessage temp=(TheMessage)arg0;
				TheMessage trunk=null;
				do
				{
					trunk=temp.Trunk();
					Messages.addElement(temp);
					temp=trunk;
				}
				while(trunk!=null);
			}
			
			public void addDataChangedListener(DataChangedListener arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		back = new Command("Back", 0);
		send = new Command("Send", 1);
		list.setListCellRenderer(new MyListCellRenderer());
		list.setFixedSelection(List.FIXED_NONE_CYCLIC);
		chatspace = new TextField();
		this.addComponent(BorderLayout.SOUTH,chatspace);
		this.addComponent(BorderLayout.CENTER,list);		
		this.addCommand(back);
		this.addCommand(send);
		this.addCommandListener(this);
	}

	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		Command cmd=arg0.getCommand();
		switch(cmd.getId())
		{
		case 0:
			display.main_menu.show();
			break;
		case 1:
			String context=chatspace.getText();
			if(context!="")
			{				
				TheMessage temp=new TheMessage(context, 1);
				list.addItem(temp);
				try {
					String response=getBirthdayFromNameUsingPost(context);
					temp=new TheMessage(response, 0);
					list.addItem(temp);
					chatspace.setText("");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				this.repaint();
			}
			break;
		}
	}
	
	public String getBirthdayFromNameUsingPost(String name) throws IOException {

		HttpConnection httpConn = null;
		String url = "http://www.pandorabots.com/pandora/talk-xml?botid=f5d922d97e345aa1";
		InputStream is = null;
		OutputStream os = null;
		String content = "";

		try {
			// Open an HTTP Connection object
			httpConn = (HttpConnection) Connector.open(url);
			// Setup HTTP Request to POST
			httpConn.setRequestMethod(HttpConnection.POST);

			httpConn.setRequestProperty("User-Agent",
					"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
			httpConn.setRequestProperty("Accept_Language", "en-US");
			// Content-Type is must to pass parameters in POST Request
			httpConn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

			// This function retrieves the information of this connection
			// getConnectionInformation(httpConn);

			os = httpConn.openOutputStream();

			String params;
			params = "input=" + name;

			os.write(params.getBytes());

			/**
			 * Caution: os.flush() is controversial. It may create unexpected
			 * behavior on certain mobile devices. Try it out for your mobile
			 * device
			 **/

			// os.flush();

			// Read Response from the Server

			StringBuffer sb = new StringBuffer();
			is = httpConn.openDataInputStream();
			int chr;
			while ((chr = is.read()) != -1)
				sb.append((char) chr);

			// Web Server just returns the birthday in mm/dd/yy format.
			// System.out.println(name+"'s Birthday is " + sb.toString());

			content = sb.toString();
			
			int iBegin = -1;
			int iEnd = -1;

			iBegin = content.indexOf("<that>", 0) + 6;
			if (iBegin != -1)
				iEnd = content.indexOf("</that>", iBegin);
			return content.substring(iBegin, iEnd);
		} finally {
			if (is != null)
				is.close();
			if (os != null)
				os.close();
			if (httpConn != null)
				httpConn.close();
		}
	}
}
